package com.example.musicrecommend.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.musicrecommend.common.BaseResponse;
import com.example.musicrecommend.common.ErrorCode;
import com.example.musicrecommend.common.ResultUtils;
import com.example.musicrecommend.exception.BusinessException;
import com.example.musicrecommend.exception.ThrowUtils;
import com.example.musicrecommend.model.dto.user.UserLoginRequest;
import com.example.musicrecommend.model.dto.user.UserSignupRequest;
import com.example.musicrecommend.model.dto.user.UserUpdateRequest;
import com.example.musicrecommend.model.entity.User;
import com.example.musicrecommend.model.vo.UserVO;
import com.example.musicrecommend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Resource
    private UserService userService;

    //TODO:
    private final String DefaultAvatarUrl = "https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png";

    /**
     * signup ,add
     *
     * @param userSignupRequest
     * @param request
     * @return
     */
    @PostMapping("/signup")
    public BaseResponse<Long> signup(@RequestBody UserSignupRequest userSignupRequest, HttpServletRequest request) {

        if (userSignupRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userSignupRequest, user);
        // 校验
        userService.validUser(user, true);

        String account = user.getAccount();

        // 用户存在判断
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(account), "account", account);


        long count = userService.count(queryWrapper);
        // 已注册
        if(count > 0) {
            return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(),-1L,"账号已注册");
        }

        // 未注册
        //default name : user_account
        //default avatar url :
        user.setName("user_"+user.getAccount());
        user.setAvatar(DefaultAvatarUrl);
        boolean result = userService.save(user);

        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);


        return ResultUtils.success(user.getId());

    }


    /**
     * login
     *
     * @param userLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<Long> login(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {

        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User user = new User();
        BeanUtils.copyProperties(userLoginRequest, user);
        // 校验
//        userService.validUser(user, false);

//        Long id = user.getId();
        String account = user.getAccount();
        String password = user.getPassword();


        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq(id != null && id != 0, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(account), "account", account);
//        queryWrapper.eq(StringUtils.isNotBlank(password), "password", password);

        User curUser = userService.getOne(queryWrapper);

        // 账号未注册
        if(curUser == null) {
            return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(),-1L,"账号不存在");
        }

        boolean result = Objects.equals(curUser.getPassword(), password);
        if(!result) {
            return new BaseResponse<>(ErrorCode.PARAMS_ERROR.getCode(),-1L,"账号密码错误");
        }
        // TODO:token??
        return ResultUtils.success(curUser.getId());

    }


    @GetMapping("/info/{id}")
    public BaseResponse<UserVO> getInfoById(@PathVariable Long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id<=0,ErrorCode.PARAMS_ERROR);

        User user = userService.getById(id);
        ThrowUtils.throwIf(user==null,ErrorCode.NOT_FOUND_ERROR);
        UserVO info =  new UserVO();
        BeanUtils.copyProperties(user,info);


        return ResultUtils.success(info);
    }


    /**
     * 更新User
     *
     * @param userUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest,
                                                HttpServletRequest request) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        // 校验
        userService.validUser(user, false);

        User oldUser = userService.getById(user.getId());
        ThrowUtils.throwIf(oldUser == null, ErrorCode.NOT_FOUND_ERROR);

        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }




}
